import { SearchOutlined, SyncOutlined, PlusOutlined, DeleteOutlined } from '@ant-design/icons'
import { Button, Form, Input, Select, Table, Card, message, Tag, Popconfirm, Popover, Modal, Transfer, Spin } from 'antd'
import { Store } from 'rc-field-form/lib/interface'
import React, { useState, useEffect } from 'react'
import '../../DepartmentManage/views/style.css'
import TableToolbar from '../../../components/TableSetting/TableToolbar'
import { fetchRequest } from '../../../utils/Request'
import { url } from '../../../utils/url'
import { useDispatch, useSelector } from 'react-redux'
import actionType from '../actionType'
import { useRequest, useUnmount } from '@umijs/hooks'

interface RequestParams {
    devName: string,
    devLocation: string,
    deptID: string
}

interface DevSelect {
    targetKeys: string[],
    selectedKeys: string[],
}

interface ModifyParams {
    deptID: string,
    devList: string[]
}

export default function EquipmentTable() {

    const devInfo = useSelector((state: any) => {
        return state.devManage;
    })

    const columns = [{
        title: '设备名称',
        dataIndex: 'devName',
        key: 'devName'
    }, {
        title: "所属部门",
        dataIndex: "orzName",
        key: "orzName"
    }, {
        title: "设备状态",
        dataIndex: "state",
        key: "state"
    }, {
        title: "设备位置描述",
        dataIndex: "devLocation",
        key: 'devLocation'
    }, {
        title: "操作", key: "opeartion",
        render: (record: any) => <Popconfirm title="确定要删除？" onConfirm={(e: any) => { deleteDev.run({ devID: record.deviceID }) }}>
            <Tag className="tags-hover" color="#f50" icon={<DeleteOutlined />}>删除</Tag>
        </Popconfirm>
    }]

    const [form] = Form.useForm()

    //点击搜索按钮
    function handleFinish(values: Store) {
        // console.log(values)
        dispatch({ type: actionType.SET_PARAMS, payload: { devName: typeof values.devName === "undefined" ? "" : values.devName, devLocation: typeof values.devLocation === "undefined" ? "" : values.devLocation } })
    }

    //点击重置按钮
    function handleReset() {
        // console.log(values)
        form.resetFields();
        dispatch({ type: actionType.SET_PARAMS, payload: { devName: "", devLocation: "" } })
        //TODO 后续请求数据
    }

    //查询框
    const searchForm = (<Card className="search-form"> <Form form={form} layout="inline" initialValues={{ deptState: "1" }} onFinish={handleFinish} onReset={handleReset}>

        <Form.Item className="form-control-item" name="devName" label="设备名称">
            <Input className="search-form-item" />
        </Form.Item>

        <Form.Item className="form-control-item" name="devLocation" label="设备位置描述">
            <Input className="search-form-item" />
        </Form.Item>

        {/* <Form.Item className="form-control-item" name="devLocation" label="设备位置">
            <Input className="search-form-item" />
        </Form.Item> */}


        <Form.Item className="form-control-item" >
            <Button type="primary" icon={<SearchOutlined />} htmlType="submit" style={{ marginRight: '8px' }}>搜索</Button>
            <Button icon={<SyncOutlined />} htmlType="reset">重置</Button>

        </Form.Item>

    </Form></Card>)

    const [columnsKey, setcolumnsKey] = useState<any[]>([])

    const [realColumns, setrealColumns] = useState<any[]>([])

    const [devList, setdevList] = useState<DevSelect>({
        targetKeys: [],
        selectedKeys: []
    })

    const [manageList, setmanageList] = useState<any[]>([])

    const [addVisible, setaddVisible] = useState<boolean>(false)

    //点击刷新按钮
    function onRefresh() {
        // getDept.run()
        getDevTable.run(devInfo.requestParams)
    }

    //点击新增按钮
    function onAdd() {
        // setaddVisible({ visible: true, deptID: undefined })
        getSelected.run()
        setaddVisible(true)
    }

    function onColumnsChange(checkedList: any[]) {
        setcolumnsKey(checkedList)
    }


    //监听变化
    useEffect(() => {
        const realColumns = columns.filter(item => columnsKey.indexOf(item.key) !== -1)
        setrealColumns(realColumns)
    }, [columnsKey])


    const dispatch = useDispatch()


    //得到设备
    async function getDeptDevTable(params: RequestParams) {
        try {
            const json = await fetchRequest(url.GET_DEPT_DEV_TABLE, params);
            if (json.success) {
                dispatch({ type: actionType.GET_DEV_TABLE, payload: json.data })
            } else {
                message.destroy();
                message.error(json.error);
            }
        } catch (error:any) {
            message.destroy();
            message.error(error.message)
        }
    }

    const getDevTable = useRequest(getDeptDevTable, {
        manual: true,
        loadingDelay: 200
    })



    useEffect(() => {
        getDevTable.run(devInfo.requestParams)

    }, [devInfo.requestParams])

    const getSelectable = useRequest(getDeptSelectableInfo, {
        loadingDelay: 200
    })

    const getSelected = useRequest(getSelectedDevInfo, {
        loadingDelay: 200,
        manual: true
    })

    //得到部门可选择的设备信息
    async function getDeptSelectableInfo() {
        try {
            const json = await fetchRequest(url.GET_DEPT_DEV_LIST, "");
            if (json.success) {
                const data: any[] = [];
                json.data.map((item: any) => {
                    data.push({ key: item.label, title: item.value })
                })
                setmanageList(data)
            } else {
                message.destroy();
                message.error(json.error)
            }
        } catch (error:any) {
            message.destroy();
            message.error(error.message)
        }
    }

    //得到已选择的设备
    async function getSelectedDevInfo() {
        try {
            const json = await fetchRequest(url.GET_DEPT_SELECTED_DEV_LIST, { deptID: devInfo.requestParams.deptID });
            if (json.success) {
                const data: string[] = [];
                json.data.map((item: any) => {
                    data.push(item.label)
                })
                setdevList({ ...devList, targetKeys: data })
            } else {
                message.destroy();
                message.error(json.error);
            }
        } catch (error:any) {
            message.destroy();
            message.error(error.message)

        }
    }

    function onOk() {
        const params: ModifyParams = { deptID: devInfo.requestParams.deptID, devList: devList.targetKeys }
        modify.run(params);
    }


    const modify = useRequest(modifyDevList, {
        manual: true,
        loadingDelay: 200
    })

    //删除设备的接口
    async function deleteDevRequest(params: { devID: string }) {

        const param = { ...params, deptID: devInfo.requestParams.deptID }
        try {
            const json = await fetchRequest(url.DELETE_DEPT_DEV_URL, param);
            if (json.success) {
                message.destroy();
                message.success("删除成功！");
                getDevTable.run(devInfo.requestParams)
            } else {
                message.destroy();
                message.error(json.error)
            }
        } catch (error:any) {
            message.destroy();
            message.error(error.message)
        }
    }


    const deleteDev = useRequest(deleteDevRequest, {
        manual: true,
        loadingDelay: 200
    })

    //修改设备
    async function modifyDevList(params: ModifyParams) {
        try {
            const json = await fetchRequest(url.MODIFY_DEOT_DEV, params);
            if (json.success) {
                message.destroy();
                message.success("分配成功!");
                setaddVisible(false)
                getDevTable.run(devInfo.requestParams)
            } else {
                message.destroy();
                message.error(json.error)
            }
        } catch (error:any) {
            message.destroy();
            message.error(error.message)
        }
    }


    useUnmount(() => {
        dispatch({
            type: actionType.SET_PARAMS, payload: {
                deptID: "",
                devName: "",
                devLocation: ""
            }
        })
    })

    return (
        <div>
            {searchForm}
            <Card className="search-form-table">
                <TableToolbar buttonText="配置" tableName="分配设备表" columns={columns} onColumnsChange={onColumnsChange} onRefresh={onRefresh} onAdd={onAdd} />
                <Table rowKey={(record: any) => record.deviceCode} pagination={{ hideOnSinglePage: true, simple: true, showSizeChanger: false }} loading={getDevTable.loading} columns={realColumns} dataSource={devInfo.devTableList} />
            </Card>

            <Modal width="600px" title="分配设备" visible={addVisible} destroyOnClose onCancel={() => {
                setaddVisible(false);
            }} onOk={onOk} confirmLoading={modify.loading}>
                <Spin spinning={getSelected.loading || getSelectable.loading}>
                    <Transfer
                        showSearch
                        listStyle={{
                            width: 250,
                            height: 300,
                        }}
                        dataSource={manageList}
                        titles={['可选设备', '已选设备']}
                        targetKeys={devList.targetKeys}
                        selectedKeys={devList.selectedKeys}
                        onChange={handleChange}
                        onSelectChange={handleSelectChange}
                        render={(record: any) => record.title}
                    />
                </Spin>
            </Modal>
        </div>
    )



    //把选项添加到已选择设备中
    function handleChange(nextTargetKeys: string[]) {
        // this.setState({ targetKeys: nextTargetKeys });
        setdevList({ ...devList, targetKeys: nextTargetKeys })
    };
    //点击选中的时候
    function handleSelectChange(sourceSelectedKeys: string[], targetSelectedKeys: string[]) {
        // this.setState({ selectedKeys: [...sourceSelectedKeys, ...targetSelectedKeys] });
        setdevList({
            ...devList, selectedKeys: [...sourceSelectedKeys, ...targetSelectedKeys]
        })

    };
}
